/**
 * 敌机系统 - 管理敌机生成、AI行为和攻击
 */
import { System, World, Entity } from '../ecs';
import { Transform, Renderer, Collider, Health, Weapon, EnemyAI, Bullet } from '../components';

export class EnemySystem implements System {
  priority = 30;
  private spawnTimer = 0;
  private spawnInterval = 2; // 每2秒生成一个敌机

  update(deltaTime: number, world: World): void {
    this.updateEnemyAI(world, deltaTime);
    this.updateEnemyWeapons(world, deltaTime);
    this.spawnEnemies(world, deltaTime);
    this.cleanupOffscreenEnemies(world);
  }

  private updateEnemyAI(world: World, deltaTime: number): void {
    const enemies = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('enemyAI')
    );
    
    for (const enemy of enemies) {
      const transform = enemy.getComponent<Transform>('transform')!;
      const ai = enemy.getComponent<EnemyAI>('enemyAI')!;
      
      ai.patternTime += deltaTime;
      
      switch (ai.movePattern) {
        case 'straight':
          transform.velocityY = 150; // 直线向下移动
          break;
          
        case 'zigzag':
          transform.velocityY = 120;
          transform.velocityX = Math.sin(ai.patternTime * 3) * 100;
          break;
          
        case 'circle':
          const radius = 80;
          const speed = 2;
          transform.velocityX = Math.cos(ai.patternTime * speed) * radius - transform.x;
          transform.velocityY = Math.sin(ai.patternTime * speed) * radius + 100;
          break;
      }
    }
  }

  private updateEnemyWeapons(world: World, deltaTime: number): void {
    const currentTime = performance.now() / 1000;
    const enemies = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('weapon') && e.hasComponent('enemyAI')
    );
    
    for (const enemy of enemies) {
      const transform = enemy.getComponent<Transform>('transform')!;
      const weapon = enemy.getComponent<Weapon>('weapon')!;
      
      // 检查是否可以开火
      if (currentTime - weapon.lastFireTime >= weapon.fireRate) {
        this.fireEnemyBullet(world, transform, weapon);
        weapon.lastFireTime = currentTime;
      }
    }
  }

  private fireEnemyBullet(world: World, transform: Transform, weapon: Weapon): void {
    const bullet = new Entity()
      .addComponent('transform', {
        x: transform.x,
        y: transform.y + 20,
        rotation: Math.PI, // 向下射击
        velocityX: 0,
        velocityY: weapon.bulletSpeed
      })
      .addComponent('renderer', {
        color: '#ff4444',
        radius: 4,
        shape: 'circle' as const
      })
      .addComponent('collider', {
        radius: 4,
        isTrigger: true,
        layer: 'enemyBullet'
      })
      .addComponent('bullet', {
        damage: weapon.damage,
        owner: 'enemy' as const,
        lifeTime: 0,
        maxLifeTime: 5
      });

    world.addEntity(bullet);
  }

  private spawnEnemies(world: World, deltaTime: number): void {
    this.spawnTimer += deltaTime;
    
    if (this.spawnTimer >= this.spawnInterval) {
      this.spawnRandomEnemy(world);
      this.spawnTimer = 0;
      
      // 随着时间推移，生成间隔逐渐缩短
      this.spawnInterval = Math.max(0.5, this.spawnInterval - 0.05);
    }
  }

  private spawnRandomEnemy(world: World): void {
    const { width } = world.resources;
    const enemyTypes = ['scout', 'destroyer', 'mothership'] as const;
    const type = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
    
    let enemy: Entity;
    const x = Math.random() * (width - 100) + 50;
    
    switch (type) {
      case 'scout':
        enemy = this.createScoutEnemy(x);
        break;
      case 'destroyer':
        enemy = this.createDestroyerEnemy(x);
        break;
      case 'mothership':
        enemy = this.createMothershipEnemy(x);
        break;
    }
    
    world.addEntity(enemy);
  }

  private createScoutEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -30, rotation: Math.PI,
        velocityX: 0, velocityY: 150
      })
      .addComponent('renderer', {
        color: '#ff6666',
        radius: 12,
        shape: 'triangle' as const
      })
      .addComponent('collider', {
        radius: 12,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 25,
        max: 25
      })
      .addComponent('weapon', {
        fireRate: 2,
        lastFireTime: 0,
        damage: 10,
        bulletSpeed: 200,
        bulletColor: '#ff4444'
      })
      .addComponent('enemyAI', {
        type: 'scout',
        movePattern: 'zigzag',
        patternTime: 0
      });
  }

  private createDestroyerEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -40, rotation: Math.PI,
        velocityX: 0, velocityY: 100
      })
      .addComponent('renderer', {
        color: '#ff3333',
        radius: 18,
        shape: 'square' as const
      })
      .addComponent('collider', {
        radius: 18,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 75,
        max: 75
      })
      .addComponent('weapon', {
        fireRate: 1.2,
        lastFireTime: 0,
        damage: 20,
        bulletSpeed: 250,
        bulletColor: '#ff2222'
      })
      .addComponent('enemyAI', {
        type: 'destroyer',
        movePattern: 'straight',
        patternTime: 0
      });
  }

  private createMothershipEnemy(x: number): Entity {
    return new Entity()
      .addComponent('transform', {
        x, y: -50, rotation: Math.PI,
        velocityX: 0, velocityY: 60
      })
      .addComponent('renderer', {
        color: '#cc0000',
        radius: 25,
        shape: 'circle' as const
      })
      .addComponent('collider', {
        radius: 25,
        isTrigger: false,
        layer: 'enemy'
      })
      .addComponent('health', {
        current: 200,
        max: 200
      })
      .addComponent('weapon', {
        fireRate: 0.8,
        lastFireTime: 0,
        damage: 30,
        bulletSpeed: 180,
        bulletColor: '#ff0000'
      })
      .addComponent('enemyAI', {
        type: 'mothership',
        movePattern: 'circle',
        patternTime: 0
      });
  }

  private cleanupOffscreenEnemies(world: World): void {
    const { height } = world.resources;
    const enemies = Array.from(world.entities).filter(e => 
      e.hasComponent('transform') && e.hasComponent('enemyAI')
    );
    
    for (const enemy of enemies) {
      const transform = enemy.getComponent<Transform>('transform')!;
      
      // 如果敌机移出屏幕下方，删除它
      if (transform.y > height + 50) {
        world.removeEntity(enemy);
      }
    }
  }
}